<template>
  <div
    class="login-page min-h-screen w-full bg-gradient-to-br from-blue-50 via-purple-50 to-pink-50 flex items-center justify-center p-4"
  >
    <LoadingSpinner :visible="loading" text="登录中..." />

    <div class="w-full max-w-md">
      <!-- 登录卡片 -->
      <div class="bg-white rounded-2xl shadow-xl p-8 border border-gray-100">
        <!-- Logo和标题 -->
        <div class="text-center mb-8">
          <h1
            class="text-2xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent"
          >
            AI管理平台
          </h1>
          <p class="text-gray-500 mt-2">欢迎回来，请登录您的账号</p>
        </div>

        <!-- 登录表单 -->
        <a-form
          ref="formRef"
          :model="loginForm"
          :rules="rules"
          @submit="handleLogin"
          layout="vertical"
          :style="{ width: '100%' }"
        >
          <!-- 用户名输入框 -->
          <a-form-item field="username" hide-asterisk>
            <a-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :style="{ width: '100%', height: '48px', borderRadius: '12px' }"
              allow-clear
            >
              <template #prefix>
                <div class="flex items-center h-full px-3">
                  <BaseIcon
                    name="icon-user"
                    :style="{ color: loginForm.username ? '#1955ff' : '#86909c' }"
                  />
                </div>
              </template>
            </a-input>
          </a-form-item>

          <!-- 密码输入框 -->
          <a-form-item field="password" hide-asterisk>
            <a-input-password
              v-model="loginForm.password"
              placeholder="请输入密码"
              :style="{ width: '100%', height: '48px', borderRadius: '12px' }"
              allow-clear
            >
              <template #prefix>
                <div class="flex items-center h-full px-3">
                  <BaseIcon
                    name="icon-lock"
                    :style="{ color: loginForm.password ? '#1955ff' : '#86909c' }"
                  />
                </div>
              </template>
            </a-input-password>
          </a-form-item>

          <!-- 验证码输入框 -->
          <a-form-item v-if="captchaRequired" field="captcha" hide-asterisk>
            <CaptchaVerify
              :key="captchaKey"
              v-model:visible="captchaRequired"
              @verify-success="handleCaptchaSuccess"
              @verify-failed="handleCaptchaFailed"
            />
          </a-form-item>

          <!-- 记住我和忘记密码 -->
          <div class="flex items-center justify-between mb-6">
            <a-checkbox v-model="loginForm.rememberMe"> 记住我 </a-checkbox>
            <a-link>忘记密码？</a-link>
          </div>

          <!-- 登录按钮 -->
          <BaseButton type="primary" size="large" html-type="submit" class="w-full mb-4">
            登 录
          </BaseButton>

          <!-- 其他登录方式 -->
          <div class="relative">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-gray-200"></div>
            </div>
            <div class="relative flex justify-center text-sm">
              <span class="px-2 bg-white text-gray-500">其他登录方式</span>
            </div>
          </div>

          <!-- 社交登录按钮 -->
          <div class="flex justify-center space-x-4 mt-4">
            <a-button
              class="!h-10 !w-10 !p-0 !rounded-full border border-gray-200"
              :style="{ color: '#333' }"
              hover
            >
              <BaseIcon name="icon-github" :size="20" />
            </a-button>
            <a-button
              class="!h-10 !w-10 !p-0 !rounded-full border border-gray-200"
              :style="{ color: '#dd4b39' }"
              hover
            >
              <BaseIcon name="icon-google" :size="20" />
            </a-button>
            <a-button
              class="!h-10 !w-10 !p-0 !rounded-full border border-gray-200"
              :style="{ color: '#07c160' }"
              hover
            >
              <BaseIcon name="icon-wechat" :size="20" />
            </a-button>
          </div>

          <!-- 注册链接 -->
          <div class="text-center mt-6 text-gray-600">
            还没有账号？
            <a-link>立即注册</a-link>
          </div>
        </a-form>
      </div>

      <!-- 页脚 -->
      <div class="text-center mt-8 text-gray-500 text-sm">
        © {{ new Date().getFullYear() }} AI管理平台. All rights reserved.
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from '@arco-design/web-vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import BaseIcon from '@/components/BaseIcon.vue'
import { useNotification } from '@/composables/useNotification'
import { responseCode } from '@/config/response-code'
import type { UserInfo, LoginResponse } from '@/types/auth'
import { authService } from '@/services/auth'
import { LoginType } from '@/config'
import { useAuthStore } from '@/stores'
import CaptchaVerify from '@/components/CaptchaVerify.vue'
import BaseButton from '@/components/BaseButton.vue'
import '@/assets/styles/components/login.css'

const router = useRouter()
const loading = ref(false)
const formRef = ref<FormInstance>()

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false,
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 4, message: '用户名长度不能小于4位' },
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 6, message: '密码长度不能小于6位' },
  ],
}

const notify = useNotification()
const authStore = useAuthStore()

const captchaRequired = ref(false)
const verifiedCaptchaId = ref<string | null>(null)
const captchaKey = ref(0)

// 验证码验证成功
const handleCaptchaSuccess = async (captchaId: string) => {
  verifiedCaptchaId.value = captchaId
  // 验证码验证成功后，不再自动触发登录
}

// 验证码验证失败
const handleCaptchaFailed = () => {
  verifiedCaptchaId.value = null
  captchaKey.value++
}

// 修改登录处理函数
const handleLogin = async () => {
  if (!formRef.value) return

  try {
    const errors = await formRef.value.validate()
    if (errors) return

    loading.value = true

    const loginParams = {
      account: loginForm.username.trim(),
      password: loginForm.password.trim(),
      ...(verifiedCaptchaId.value ? { captchaId: verifiedCaptchaId.value } : {}),
    }

    const response = await authService.loginByPassword(loginParams, LoginType.ADMIN)

    // 登录成功
    if (response && response.code === responseCode.success && 'data' in response) {
      const userInfo = response.data as UserInfo
      // 登录成功后清空验证码相关状态
      verifiedCaptchaId.value = null
      captchaRequired.value = false
      // 设置用户信息并跳转
      authStore.setUserInfo(userInfo)
      notify.success('登录成功', {
        title: '欢迎回来',
        content: `${userInfo.name}，您已成功登录系统`,
      })
      await authStore.fetchUserPermissions() // 获取用户权限
      router.push('/') // 跳转到首页
      return
    }

    // 需要验证码的情况（包括密码错误）
    if (response && response.code === responseCode.needCaptcha && 'data' in response) {
      const loginResponse = response.data as LoginResponse
      if (loginResponse && loginResponse.enableCaptchaVerify) {
        captchaRequired.value = true
        // 如果已经开启了验证码，说明是密码错误，需要刷新验证码
        if (verifiedCaptchaId.value) {
          verifiedCaptchaId.value = null
          captchaKey.value++
        }
        notify.error(response.message, {
          title: '登录失败',
        })
        return
      }
    }

    // 验证码错误的情况
    if (response && response.code === responseCode.errorCaptcha) {
      captchaRequired.value = true
      verifiedCaptchaId.value = null
      captchaKey.value++ // 验证码错误时刷新验证码
      notify.error('验证码错误，请重新验证', {
        title: '验证失败',
      })
      return
    }

    // 其他登录失败情况
    notify.error(response.message, {
      title: '登录失败',
    })
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '登录失败，请检查用户名和密码'
    notify.error(errorMessage, {
      title: '登录失败',
    })
  } finally {
    loading.value = false
  }
}
</script>
